package com.zaofan.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.zaofan.bean.BaiLocation;

/**
 *
 * @author Administrator
 */
public class Send {

	public static String sendGetUrl(String postUrl) {
		try {
			// 发送POST请求
			URL url = new URL(postUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.flush();
			out.close();

			// 获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				System.out.println("connect failed!");
				return "";
			}
			// 获取响应内容体
			String line, result = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result += line + "\n";
			}
			in.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return "";
	}

	public static BaiLocation getLocation(String address, String city) {
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=14G0unnrnofl094xF5ruisvo&output=json&address=" + address
				+ "&city=" + city;
		String result = sendGetUrl(url);
		Gson gson = new Gson();
		BaiLocation location = gson.fromJson(result, new TypeToken<BaiLocation>() {
		}.getType());
		if (location != null) {
			return location;
		}
		return location;
	}

	public static void main(String[] args) {
		String sendUrl = "http://api.map.baidu.com/geocoder/v2/?ak=14G0unnrnofl094xF5ruisvo&output=json&address=仓山区大坪路展进巷58号&city=福州市";
		System.err.println(getLocation("仓山区大坪路展进巷asdfasdf", "福州市").getStatus());
		String result = sendGetUrl(sendUrl);
		System.err.println(result);
	}
}
